package core

import (
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/rawdb"
	"github.com/ethereum/go-ethereum/log"
	"github.com/ethereum/go-ethereum/trie"
	ctypes "github.com/tendermint/tendermint/rpc/core/types"
	rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)

func MPTQuery(ctx *rpctypes.Context, blockMPTHash []byte, objectId string) (*ctypes.ResultMPTQuery, error) {
	proofDB := rawdb.NewMemoryDatabase()
	heightList, cumulativeHash, err := env.BlockStore.GetIndex(objectId, proofDB)
	if err != nil {
		log.Info(err.Error())
		return nil, err
	}

	if len(heightList) == 0 || len(cumulativeHash) == 0 {
		return &ctypes.ResultMPTQuery{}, nil
	}

	var hash common.Hash
	copy(hash[:], blockMPTHash)
	if _, err = trie.VerifyProof(hash, []byte(objectId), proofDB); err != nil {
		log.Info(err.Error())
		return nil, err
	}

	return &ctypes.ResultMPTQuery{HeightList: heightList, CumulativeHash: cumulativeHash}, nil
}
